﻿using System;
using System.Net;

namespace HCore
{
    public class Session
    {
        private readonly EndPoint _endPoint;
        private readonly uint _sessionId;
        private readonly IntPtr _kcp;

        public EndPoint endPoint => _endPoint;
        public uint sessionId => _sessionId;

        public Session(uint managerId, uint sessionId, EndPoint endPoint, kcp_output kcpOutput)
        {
            _endPoint = endPoint;
            _sessionId = sessionId;
            _kcp = Kcp.ikcp_create(NetworkDefine.CONNECTING_MAGIC_NUM,
                new IntPtr(_sessionId | (managerId << NetworkDefine.SESSION_BITS)));
            Kcp.ikcp_nodelay(_kcp, 2, 10, 2, 1);
            Kcp.ikcp_wndsize(_kcp, 128, 128);
            Kcp.ikcp_setminrto(_kcp, 10);
            Kcp.ikcp_setoutput(_kcp, kcpOutput);
        }

        public void Update(uint current)
        {
            Kcp.ikcp_update(_kcp, current);
        }

        public void Input(byte[] data, long size)
        {
            Kcp.ikcp_input(_kcp, data, size);
        }

        public int Rec(byte[] bytes, int len)
        {
            return Kcp.ikcp_recv(_kcp, bytes, len);
        }

        public int Send(byte[] bytes, int len)
        {
            return Kcp.ikcp_send(_kcp, bytes, len);
        }

        public void Dispose()
        {
            Kcp.ikcp_release(_kcp);
        }
    }
}